package cn.studyjams.s1.contest.autohello;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.maps.model.LatLng;

import java.util.ArrayList;
import java.util.List;

public class ChooseCityFragment extends DialogFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private final static String TAG = "ChooseCityFragment";

    ChooseCityListener chooseCityListener;

    EditText receiverAddressET;
    AppCompatButton searchAddressBTN;
    ListView searchAddressResultList;
    TextView searchTipsTV;

    List<String> results = new ArrayList<>();
    List<LatLng> lls = new ArrayList<>();

    public interface ChooseCityListener {
        void onConfirmChooseCity(LatLng ll, String locationName);
    }

    public ChooseCityFragment() {
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow()
                    .setLayout((int) (dm.widthPixels * 0.85), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            chooseCityListener = (ChooseCityListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + "must implement ChooseCityFragment");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_choose_city, null);

        receiverAddressET = (EditText) view.findViewById(R.id.receivers_address);
        searchAddressBTN = (AppCompatButton) view.findViewById(R.id.search_address);
        searchAddressResultList = (ListView) view.findViewById(R.id.search_address_result);
        searchTipsTV = (TextView) view.findViewById(R.id.search_tips);

        searchTipsTV.setVisibility(View.GONE);
        searchAddressBTN.setOnClickListener(this);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dismiss();
            }
        });

        return builder.create();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.search_address) {

            String addressStr = receiverAddressET.getText().toString();
            if (TextUtils.isEmpty(addressStr)) {
                receiverAddressET.setError(getString(R.string.required));
                return;
            }

            searchAddressBTN.setText(R.string.loading);
            long startTime = System.currentTimeMillis();

            List<Address> address = getLocationFromAddress(getActivity(), addressStr);

            if (address != null) {
                results.clear();
                lls.clear();

                long endTime = System.currentTimeMillis();
                searchTipsTV.setText(
                        String.format(
                                getString(R.string.search_tips),
                                address.size() + "",
                                (endTime - startTime) / 1000.0 + ""
                        )
                );
                searchTipsTV.setVisibility(View.VISIBLE);

                String resultStr;
                for (Address add : address) {
                    resultStr = "";
                    if (add.getLocality() != null) {
                        resultStr += add.getLocality() + " ";
                    }
                    if (add.getAdminArea() != null) {
                        resultStr += add.getAdminArea() + " ";
                    }
                    if (add.getCountryName() != null) {
                        resultStr += add.getCountryName();
                    }

                    if (!TextUtils.isEmpty(resultStr)) {
                        LatLng ll = new LatLng(add.getLatitude(), add.getLongitude());
                        results.add(resultStr);
                        lls.add(ll);
                    }
                }

                ArrayAdapter<String> adapter = new ArrayAdapter<>(
                        getActivity(),
                        android.R.layout.simple_list_item_1,
                        results
                );

                searchAddressResultList.setAdapter(adapter);
                searchAddressResultList.setOnItemClickListener(this);
            }
            searchAddressBTN.setText(R.string.search);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//        Snackbar.make(view, results.get(i), Snackbar.LENGTH_LONG).show();
        ChooseCityListener listener = (ChooseCityListener) getActivity();
        listener.onConfirmChooseCity(lls.get(i), results.get(i));
        dismiss();
    }


    private List<Address> getLocationFromAddress(Context context, String strAddress) {
        Geocoder coder = new Geocoder(context);
        List<Address> address = null;

        try {
            address = coder.getFromLocationName(strAddress, 5);
            if (address == null) {
                return null;
            }
        } catch (Exception ex) {
            Log.d(TAG, ex.toString());
        }

        return address;
    }
}
